package com.sq.controller;

import com.sq.common.web.R;
import com.sq.dto.FileDto;
import com.sq.service.minio.IFileMinioService;
import io.minio.GetObjectArgs;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Value("${minioServerIp}")
    private String minioServerIp;
    @Autowired
    IFileMinioService fileMinioService;
    @PostMapping("/upload")
    public R<String> upload(@RequestBody FileDto fileDto) {
        FileDto fileDto1=new FileDto();
        fileDto1.setFileName(fileDto.getFileName());
        fileDto1.setBase64(fileDto.getBase64());
        fileDto1.setFileType("jpg");
        fileDto1.setMultipartFile(null);
        fileDto1.setBucketName("test");
        fileDto1.setFilePath("");
        String uploadPath = fileMinioService.upload(fileDto1);
        return R.ok(uploadPath);
    }
    @PostMapping("/uploadMultipartFileList")
    public R<String> uploadFile(@RequestParam("file") MultipartFile file,@RequestParam("bucketName") String bucketName,@RequestParam("id")Long id) {
        System.out.println(Objects.requireNonNull(file.getOriginalFilename()));
        FileDto fileDto = new FileDto();
        String imageName=file.getOriginalFilename();
        int dotIndex = imageName.lastIndexOf('.');
        String suffix = imageName.substring(dotIndex + 1);
        String prefix= imageName.substring(0, dotIndex);;
        fileDto.setFileName(id.toString());
        fileDto.setFilePath("");
        fileDto.setFileType(suffix);
        fileDto.setMultipartFile(file);
        fileDto.setBase64("");
        fileDto.setBucketName("test");
        String uploadPath = fileMinioService.upload(fileDto);
        return R.ok(minioServerIp+"/file/image/"+fileDto.getBucketName()+uploadPath);
    }

    @GetMapping("/image/{bucket}/{*objectName}")
    public void getImage(@PathVariable(name = "bucket") String bucket, @PathVariable(name="objectName") String objectName, HttpServletResponse response){
//         设置输出流
        response.setContentType("image/jpeg");
        response.setStatus(HttpServletResponse.SC_OK);
        InputStream inputStream =null;
        try{
            GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(bucket).object(objectName).build();
             inputStream = fileMinioService.getFile(objectArgs);
            if(inputStream != null) {
                // 将输入流的内容写入到输出流中，以流的形式发送给客户端
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    response.getOutputStream().write(buffer, 0, bytesRead);
                }
                // 关闭流
                response.getOutputStream().flush();
                response.getOutputStream().close();
                inputStream.close();
            }
        }catch (Exception e){
           log.error(e.getMessage());
        }finally {
            if(inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                   log.error(e.getMessage());
                }
            }
        }
        // 获取MinIO中的对象作为输入流

    }
}
